package middlewares

import (
	"net/http"
	"qimo_work/utils"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization token is missing"})
			c.Abort()
			return
		}

		// 验证 JWT
		claims, err := utils.ValidateJWT(token)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired token"})
			c.Abort()
			return
		}

		// 确保 UserID 是 uint 类型
		userID := uint(claims.UserID)

		// 将用户 ID 存入上下文
		c.Set("userID", userID)

		// 继续处理请求
		c.Next()
	}
}
